package com.example.mall.security.config;

import com.example.mall.security.handler.JwtHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author ：Dongdequan
 * @date ：Created in 2022/5/26 9:40
 * @modified By：
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtHandler jwtHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        /* 开启跨域共享,跨域伪造请求限制=无效 */
        http.cors().and().csrf().disable()
                .authorizeRequests()
                //swagger-ui
                .antMatchers("/img/**",
                        "/swagger-ui.html",
                "/swagger-resources/**",
                "/webjars/**",
                "/v2/**",
                "/api/**").permitAll()
                .antMatchers("/user/login").permitAll()
                .anyRequest().authenticated()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .formLogin().disable()
                .headers().cacheControl();
        /* 配置token验证过滤器 */
        http.addFilterBefore(jwtHandler, UsernamePasswordAuthenticationFilter.class);
    }
}
